package services;

import domain.entities.Specialty;
import domain.entities.TherapeuticArea;
import domain.entities.TherapeuticAreaDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Guillermo
 * Date: 23/08/12
 * Time: 16:54
 * To change this template use File | Settings | File Templates.
 */
@Service
public class TherapeuticAreaCRUDService implements CRUDService<TherapeuticArea>{

    private TherapeuticAreaDAO therapeuticAreaDAO;

    public TherapeuticAreaCRUDService() {
    }

    @Autowired
    public TherapeuticAreaCRUDService(TherapeuticAreaDAO therapeuticAreaDAO)   {
        this.therapeuticAreaDAO = therapeuticAreaDAO;
    }

    @Override
    public <V extends Criteria> List<TherapeuticArea> list(V criteria) {
        List<TherapeuticArea> list =  therapeuticAreaDAO.findAll();
                Iterator<TherapeuticArea> it = list.iterator();
        while(it.hasNext()){
            if(!criteria.isIn(it.next())){
                it.remove();
            }
        }
        return list;
    }

    public List<TherapeuticArea> list() {
        return  therapeuticAreaDAO.findAll();
    }

    public TherapeuticArea findById(int id){
        return (TherapeuticArea) therapeuticAreaDAO.findById(id);
    }

    public void save(TherapeuticArea therapeuticArea){
        ArrayList<Specialty> aux = new ArrayList<Specialty>(0);
        for(Specialty s : therapeuticArea.getSpecialities()){
            if(s == null || s.getName() == null || s.getName().equals("")){
                aux.add(s);
            }
        }
        therapeuticArea.getSpecialities().removeAll(aux);
        therapeuticAreaDAO.attachDirty((domain.entities.TherapeuticArea) therapeuticArea);
    }

    public void delete(TherapeuticArea therapeuticArea) {
        therapeuticAreaDAO.delete((domain.entities.TherapeuticArea) therapeuticArea);
    }
}
